/**
 * 数据同步管理相关的 Composables
 * 提取可复用的逻辑，提高代码组织性和性能
 */
import { ref, reactive, computed, shallowRef, watchEffect } from 'vue'
import { message } from 'ant-design-vue'
import syncApi from '@/apis/sync_api'

/**
 * 数据源管理 Composable
 */
export function useDataSources() {
  // 使用 shallowRef 优化大型数组的性能
  const dataSources = shallowRef([])
  const loading = ref(false)
  const pagination = reactive({
    current: 1,
    pageSize: 20,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total) => `共 ${total} 条数据`
  })

  // 筛选条件
  const filters = reactive({
    db_type: undefined
  })

  // 计算属性：优化的分页参数
  const paginationParams = computed(() => ({
    page: pagination.current,
    page_size: pagination.pageSize,
    ...filters
  }))

  // 加载数据源列表
  const loadDataSources = async () => {
    try {
      loading.value = true
      const response = await syncApi.getDataSources(paginationParams.value)
      dataSources.value = response.items
      pagination.total = response.total
    } catch (error) {
      message.error('加载数据源列表失败：' + (error.message || '未知错误'))
    } finally {
      loading.value = false
    }
  }

  // 测试连接
  const testConnection = async (dataSourceId) => {
    try {
      loading.value = true
      const response = await syncApi.testConnection(dataSourceId)

      if (response.success) {
        message.success(`连接成功！发现 ${response.available_tables.length} 个表`)
      } else {
        message.error(`连接失败：${response.message}`)
      }

      await loadDataSources()
    } catch (error) {
      message.error('测试连接失败：' + (error.message || '未知错误'))
    } finally {
      loading.value = false
    }
  }

  // 删除数据源
  const deleteDataSource = async (id) => {
    try {
      await syncApi.deleteDataSource(id)
      message.success('删除成功')
      await loadDataSources()
    } catch (error) {
      message.error('删除失败：' + (error.message || '未知错误'))
    }
  }

  // 处理分页变化
  const handlePaginationChange = (newPagination) => {
    pagination.current = newPagination.current
    pagination.pageSize = newPagination.pageSize
    loadDataSources()
  }

  // 处理筛选变化
  const handleFilterChange = () => {
    pagination.current = 1
    loadDataSources()
  }

  return {
    dataSources,
    loading,
    pagination,
    filters,
    loadDataSources,
    testConnection,
    deleteDataSource,
    handlePaginationChange,
    handleFilterChange
  }
}

/**
 * 同步任务管理 Composable
 */
export function useSyncTasks() {
  const syncTasks = shallowRef([])
  const loading = ref(false)
  const selectedRowKeys = ref([])

  const pagination = reactive({
    current: 1,
    pageSize: 20,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total) => `共 ${total} 条数据`
  })

  const filters = reactive({
    task_name: '',
    sync_status: undefined,
    sync_mode: undefined
  })

  // 计算属性：优化的分页参数
  const paginationParams = computed(() => ({
    page: pagination.current,
    page_size: pagination.pageSize,
    ...Object.fromEntries(
      Object.entries(filters).filter(([_, value]) => value !== undefined && value !== '')
    )
  }))

  // 行选择配置
  const rowSelection = computed(() => ({
    selectedRowKeys: selectedRowKeys.value,
    onChange: (keys) => {
      selectedRowKeys.value = keys
    }
  }))

  // 加载同步任务列表
  const loadSyncTasks = async () => {
    try {
      loading.value = true
      const response = await syncApi.getSyncTasks(paginationParams.value)
      syncTasks.value = response.items
      pagination.total = response.total
    } catch (error) {
      message.error('加载同步任务列表失败：' + (error.message || '未知错误'))
    } finally {
      loading.value = false
    }
  }

  // 执行同步任务
  const executeTask = async (taskId) => {
    try {
      const response = await syncApi.executeSyncTask(taskId)
      message.success(`同步任务已启动，执行ID：${response.execution_id}`)

      // 延迟刷新以显示状态变化
      setTimeout(() => {
        loadSyncTasks()
      }, 1000)
    } catch (error) {
      message.error('执行任务失败：' + (error.message || '未知错误'))
    }
  }

  // 批量执行同步任务
  const batchExecuteTasks = async (taskIds) => {
    if (taskIds.length === 0) {
      message.warning('请选择要执行的任务')
      return
    }

    try {
      const response = await syncApi.batchExecuteSyncTasks({ task_ids: taskIds })
      message.success(`批量执行完成：成功 ${response.successful_tasks} 个，失败 ${response.failed_tasks} 个`)
      selectedRowKeys.value = []

      setTimeout(() => {
        loadSyncTasks()
      }, 1000)
    } catch (error) {
      message.error('批量执行失败：' + (error.message || '未知错误'))
    }
  }

  // 删除同步任务
  const deleteTask = async (id) => {
    try {
      await syncApi.deleteSyncTask(id)
      message.success('删除成功')
      await loadSyncTasks()
    } catch (error) {
      message.error('删除失败：' + (error.message || '未知错误'))
    }
  }

  // 切换任务状态
  const toggleTask = async (task) => {
    try {
      if (task.is_active) {
        await syncApi.deactivateSyncTask(task.id)
        message.success('任务已禁用')
      } else {
        await syncApi.activateSyncTask(task.id)
        message.success('任务已启用')
      }
      await loadSyncTasks()
    } catch (error) {
      message.error('操作失败：' + (error.message || '未知错误'))
    }
  }

  const handlePaginationChange = (newPagination) => {
    pagination.current = newPagination.current
    pagination.pageSize = newPagination.pageSize
    loadSyncTasks()
  }

  const handleFilterChange = () => {
    pagination.current = 1
    loadSyncTasks()
  }

  return {
    syncTasks,
    loading,
    pagination,
    filters,
    selectedRowKeys,
    rowSelection,
    loadSyncTasks,
    executeTask,
    batchExecuteTasks,
    deleteTask,
    toggleTask,
    handlePaginationChange,
    handleFilterChange
  }
}

/**
 * 同步日志管理 Composable
 */
export function useSyncLogs() {
  const syncLogs = shallowRef([])
  const loading = ref(false)

  const pagination = reactive({
    current: 1,
    pageSize: 20,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total) => `共 ${total} 条数据`
  })

  const filters = reactive({
    status: undefined,
    dateRange: null,
    task_id: undefined
  })

  // 计算属性：优化的分页参数
  const paginationParams = computed(() => {
    const params = {
      page: pagination.current,
      page_size: pagination.pageSize
    }

    // 处理日期范围
    if (filters.dateRange && filters.dateRange.length === 2) {
      params.start_date = filters.dateRange[0].format('YYYY-MM-DD')
      params.end_date = filters.dateRange[1].format('YYYY-MM-DD')
    }

    // 添加其他筛选条件
    Object.entries(filters).forEach(([key, value]) => {
      if (value !== undefined && value !== null && key !== 'dateRange') {
        params[key] = value
      }
    })

    return params
  })

  // 加载同步日志列表
  const loadSyncLogs = async () => {
    try {
      loading.value = true
      const response = await syncApi.getSyncLogs(paginationParams.value)
      syncLogs.value = response.items
      pagination.total = response.total
    } catch (error) {
      message.error('加载同步日志失败：' + (error.message || '未知错误'))
    } finally {
      loading.value = false
    }
  }

  const handlePaginationChange = (newPagination) => {
    pagination.current = newPagination.current
    pagination.pageSize = newPagination.pageSize
    loadSyncLogs()
  }

  const handleFilterChange = () => {
    pagination.current = 1
    loadSyncLogs()
  }

  return {
    syncLogs,
    loading,
    pagination,
    filters,
    loadSyncLogs,
    handlePaginationChange,
    handleFilterChange
  }
}

/**
 * 统计信息管理 Composable
 */
export function useStatistics() {
  const statistics = shallowRef(null)
  const loading = ref(false)

  const loadStatistics = async () => {
    try {
      loading.value = true
      const response = await syncApi.getStatistics()
      statistics.value = response
    } catch (error) {
      console.error('加载统计信息失败：', error)
    } finally {
      loading.value = false
    }
  }

  return {
    statistics,
    loading,
    loadStatistics
  }
}

/**
 * 模态框状态管理 Composable
 */
export function useModals() {
  const modals = reactive({
    tableStructure: { visible: false, dataSource: null },
    dataSourceForm: { visible: false, dataSource: null, isEdit: false },
    syncTaskForm: { visible: false, dataSource: null },
    taskDetail: { visible: false, task: null },
    logDetail: { visible: false, log: null }
  })

  // 通用的模态框操作函数
  const openModal = (modalName, data = {}) => {
    if (!modals[modalName]) {
      console.error('Modal not found:', modalName)
      return
    }
    Object.assign(modals[modalName], { visible: true, ...data })
  }

  const closeModal = (modalName) => {
    modals[modalName].visible = false
    // 重置数据
    Object.keys(modals[modalName]).forEach(key => {
      if (key !== 'visible') {
        if (typeof modals[modalName][key] === 'object') {
          modals[modalName][key] = null
        } else {
          modals[modalName][key] = false
        }
      }
    })
  }

  return {
    modals,
    openModal,
    closeModal
  }
}

/**
 * 工具函数 Composable
 */
export function useSyncUtils() {
  // 格式化日期时间 - 使用计算属性优化
  const formatDateTime = computed(() => {
    return (dateTime) => {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString('zh-CN')
    }
  })

  // 格式化执行时长
  const formatDuration = (seconds) => {
    if (!seconds) return '-'
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    const secs = seconds % 60

    if (hours > 0) {
      return `${hours}小时${minutes}分钟`
    } else if (minutes > 0) {
      return `${minutes}分钟${secs}秒`
    } else {
      return `${secs}秒`
    }
  }

  // 获取状态徽章类型 - 使用计算属性优化
  const statusBadgeMap = computed(() => ({
    pending: 'default',
    running: 'processing',
    success: 'success',
    failed: 'error'
  }))

  const statusTextMap = computed(() => ({
    pending: '等待中',
    running: '运行中',
    success: '成功',
    failed: '失败'
  }))

  const getStatusBadge = (status) => statusBadgeMap.value[status] || 'default'
  const getStatusText = (status) => statusTextMap.value[status] || status

  // 获取进度百分比 - 优化计算逻辑
  const getProgressPercent = (task) => {
    if (task.sync_status === 'pending') return 0
    if (task.sync_status === 'running') {
      return task.total_records > 0
        ? Math.round((task.synced_records / task.total_records) * 100)
        : 0
    }
    if (task.sync_status === 'success') return 100
    if (task.sync_status === 'failed') {
      return task.total_records > 0
        ? Math.round((task.synced_records / task.total_records) * 100)
        : 0
    }
    return 0
  }

  const getProgressStatus = (task) => {
    if (task.sync_status === 'failed') return 'exception'
    if (task.sync_status === 'success') return 'success'
    return 'active'
  }

  return {
    formatDateTime,
    formatDuration,
    getStatusBadge,
    getStatusText,
    getProgressPercent,
    getProgressStatus
  }
}